package com.bitejiuyeke.forum.services.impl;

import com.bitejiuyeke.forum.common.AppResult;
import com.bitejiuyeke.forum.common.ResultCode;
import com.bitejiuyeke.forum.dao.UserMapper;
import com.bitejiuyeke.forum.exception.ApplicationException;
import com.bitejiuyeke.forum.model.User;
import com.bitejiuyeke.forum.services.IUserService;
import com.bitejiuyeke.forum.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;


@Service
@Slf4j
public class IUserServiceImpl implements IUserService {


    @Resource
    private UserMapper userMapper;

    /*
    * */
    @Override
    public void CreateUser(User user) {

        //非空校验
        if (user == null || StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())
        || StringUtils.isEmpty(user.getNickname())||StringUtils.isEmpty(user.getSalt())) {

            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常,统一抛出ApplicationException
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE.toString()));
        }
        //查询用户
        User users = userMapper.selectByUserName(user.getUsername());
        if (users != null) {
            log.info(ResultCode.AILED_USER_EXISTS.toString());
            //抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS.toString()));
        }
        //新增用户流程,添加默认值
       // User user1 = new User();
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        //日期设置
        Date date = new Date();
        user.setUpdateTime(date);
        user.setCreateTime(date);
        //数据库操作
        int row = userMapper.insertSelective(user);
        if (row != 1) {
            //打印日志
            log.info(ResultCode.FAILED_CREATE.toString());
            //抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE.toString()));
        }
        //新增成功
        log.info("新增用户成功 ： username = " + user.getUsername()+".");


    }
}
